package com.yesun.task.pipeline.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.boot.autoconfigure.MybatisProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.annotation.Resource;

@Configuration
@EnableTransactionManagement
public class MyBatisConfig {

    @Resource
    private DynamicDataSourceRoute dynamicDataSourceRoute;
    @Autowired
    private MybatisProperties mybatisProperties;

    //这里是最关键的，真正将我们的dynamicDataSourceRoute，更新到SqlSessionFactory
    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
        sqlSessionFactory.setDataSource(dynamicDataSourceRoute);
        sqlSessionFactory.setMapperLocations(mybatisProperties.resolveMapperLocations());
        sqlSessionFactory.setConfiguration(mybatisProperties.getConfiguration());
        return sqlSessionFactory.getObject();
    }

    @Bean
    public PlatformTransactionManager platformTransactionManager() {
        return new DataSourceTransactionManager(dynamicDataSourceRoute);
    }

}
